<?php
namespace app\admin\controller;
use app\admin\controller\Base;
use think\Db;
use \think\Request;

class Menu extends Base
{
    public function index()
    {
        $menu = Db::name('menu')->select();
        $tree = list_to_tree($menu);
        $this->assign('list',$tree);
        return $this->fetch();
    }
    /**
     * 新增菜单
     */
    public function add()
    {
        if (Request::instance()->isPost()){
            $data = input('post.');
            $result = Db::name('menu')->insert($data);
            if($result){
                $this->success('增加成功',url('admin/menu/index'));
            }else{
                $this->error('增加失败');
            }
        }else{
            $menu = Db::name('menu')->where('pid',0)->select();
            $this->assign('list',$menu);
            return $this->fetch();
        }
    }
    /**
     * 删除菜单
     */
    public function del()
    {
        $id = input('get.id');
        if(empty($id)){
            $this->error('请选择要操作的数据');
        }
        //判断是否是顶级目录，如果是，则该顶级目录下的二级目录一并删除
        $menu = Db::name('menu')->where('id',$id)->find();
        if($menu['pid'] == 0){
            $child = Db::name('menu')->where('pid',$id)->delete();
            if($child){
                $parent = Db::name('menu')->where('id',$id)->delete();
                if($parent){
                    $this->success('删除成功',url('admin/menu/index'));
                }else{
                    $this->error('删除失败');
                }
            }else{
                $this->error('删除失败');
            }
        }else{
            $result = Db::name('menu')->where('id',$id)->delete();
            if($result){
                $this->success('删除成功',url('admin/menu/index'));
            }else{
                $this->error('删除失败');
            }
        }
    }
    /**
     * 编辑菜单
     */
    public function edit()
    {
        if (Request::instance()->isPost()){
            $data = input('post.');
            $result = Db::name('menu')->where('id',$data['id'])->update($data);
            if($result){
                $this->success('修改成功',url('admin/menu/index'));
            }else{
                $this->error('修改失败');
            }
        }else{
            $id = input('get.id');
            if(empty($id)){
                $this->error('请选择要操作的数据');
            }
            $menu = Db::name('menu')->where('id',$id)->find();
            $topMenu = Db::name('menu')->where('pid',0)->select();
            $this->assign('list',$topMenu);
            $this->assign('editMenu',$menu);
            $this->assign('id',$id);
            return $this->fetch();
        }
    }
    public function test()
    {

    }
}